/**
 * @Description:登录主入口
 * @author 云离
 * @date: 2018/12/28
 */
import React, { Component } from "react";
import { actions } from "../../../../reducers/main";
import { connect } from "react-redux";
import { withRouter } from "react-router-dom";
import {
  message,
  Spin,
  Table,
  Switch,
  Button,
  Icon,
  Pagination,
  Modal,
  Tag
} from "antd";
import MyForm from "../../../components/Form";
import axios from "../../../../apis/api";
import qs from "qs";
import SettlementApplyForm from "../settlementApply/settlementApplyForm";

const mapStateToProps = (state, ownProps) => {
  return {
    vwAgentCashStat: state.main.vwAgentCashStat,
    vwAgentCashDayStat: state.main.vwAgentCashDayStat,
    isAgent: state.main.isAgent,
    isAdmin: state.main.isAdmin
  };
};

const mapDispatchToProps = dispatch => {
  return {
    fetchInitData: next => dispatch(actions.fetchInitData(next))
  };
};

class CashRecord extends Component {
  state = {
    initForm: {
      status: "",
      userName: "",
      businessNo: ""
    },
    formItmes: [],
    searchParam: {},
    loading: false,
    depMap: {},
    pageSize: 10,
    curPage: 1,
    tableData: {
      total: 0,
      rows: []
    },
    payTypes: [], // 支付类型
    payTypesMap: {},
    statusMap: {
      "3": {
        label: "已打款",
        class: "green"
      },
      "2": {
        label: "被驳回",
        class: "red"
      },
      "1": {
        label: "打款中",
        class: ""
      }
    },
    settlementApplyDig: false
  };

  handleSearch = value => {
    this.setState(
      {
        curPage: 1,
        searchParam: value
      },
      this.searchTable
    );
  };

  componentDidMount() {
    this.init();
  }

  init = async () => {
    this.getSalesman();
    this.searchTable();
  };

  getSalesman = async () => {
    const result = await axios.post("/system/user/salesman");
    const options = result.rows.map(item => {
      return {
        value: item.userId,
        label: item.userName
      };
    });
    const formItems = [
      {
        label: "业务员",
        key: "rootUserId",
        type: "select",
        options: [{ value: "", label: "所有" }, ...options]
      },
      {
        label: "状态",
        key: "status",
        type: "select",
        options: [
          {
            label: "所有",
            value: ""
          },
          {
            label: "打款中",
            value: "1"
          },
          {
            label: "被驳回",
            value: "2"
          },
          {
            label: "已打款",
            value: "3"
          }
        ]
      },
      {
        label: "用户类型",
        key: "remark",
        type: "select",
        options: [
          {
            label: "所有",
            value: ""
          },
          {
            label: "真人",
            value: "真人"
          },
          {
            label: "假人",
            value: "假人"
          }
        ]
      },
      {
        label: "会员手机号",
        key: "businessNo",
        type: "input"
      }
    ];
    this.setState({ formItmes: formItems });
  };

  searchTable = async () => {
    const { pageSize, curPage, searchParam } = this.state;
    const query = {
      orderByColumn: "applyTime",
      isAsc: "desc",
      pageSize,
      pageNum: curPage,
      status: searchParam.status,
      userName: searchParam.userName,
      remark: searchParam.remark,
      businessNo: searchParam.businessNo,
      "params[rootUserId]": searchParam.rootUserId
    };
    try {
      this.setState({
        loading: true
      });
      const result = await axios.post(
        "/channel/businessCapital/list",
        qs.stringify(query)
      );
      console.log(result);
      if (result.code === 0) {
        this.setState({
          tableData: result,
          loading: false
        });
      } else {
        this.setState({
          loading: false
        });
        message.error(result.msg);
      }
    } catch (e) {
      this.setState({
        loading: false
      });
      message.error(e.message);
    }
  };
  //翻页
  handlePageChange = (page, pageSize) => {
    this.setState(
      {
        curPage: page
      },
      this.searchTable
    );
  };
  handleOpenSettlementApplyDlg = () => {
    this.setState({
      settlementApplyDig: true
    });
  };

  handleCloseSettlementApplyDlg = () => {
    this.setState({
      settlementApplyDig: false
    });
  };

  reject = async data => {
    Modal.confirm({
      title: "系统提示",
      content: "确认进行此操作吗?",
      okText: "确定",
      cancelText: "取消",
      onOk: () => {
        this._setPayState({
          id: data.capitalId,
          status: 2
        });
      },
      onCancel() {}
    });
  };

  setAlreadyPay = async data => {
    Modal.confirm({
      title: "系统提示",
      content: "确认进行此操作吗?",
      okText: "确定",
      cancelText: "取消",
      onOk: () => {
        this._setPayState({
          id: data.capitalId,
          status: 3
        });
      },
      onCancel() {}
    });
  };
  _setPayState = async body => {
    try {
      const result = await axios.post(
        "/channel/businessCapital/editStatus",
        qs.stringify(body)
      );
      if (result.code === 0) {
        message.success(result.msg);
      } else {
        message.error(result.msg);
      }
      this.handlePageChange(1);
    } catch (e) {}
  };

  onShowSizeChange = (current, pageSize) => {
    this.setState(
      {
        pageSize: pageSize,
        curPage: current
      },
      this.searchTable
    );
  };

  render() {
    const {
      initForm,
      formItmes,
      loading,
      tableData,
      curPage,
      pageSize,
      payTypesMap,
      statusMap
    } = this.state;
    const { isAdmin } = this.props;
    const columns = [
      {
        title: "状态",
        dataIndex: "status",
        key: "status",
        render: (value, data) => {
          return (
            <Tag color={statusMap[value].class}>{statusMap[value].label}</Tag>
          );
        }
      },
      {
        title: "会员手机号",
        dataIndex: "businessNo",
        key: "businessNo"
      },
      {
        title: "业务员",
        dataIndex: "rootUserName",
        key: "rootUserName"
      },
      {
        title: "用户类型",
        dataIndex: "remark",
        key: "remark",
        render: text => {
          return text === "假人" ? (
            <Tag color="#f50">假人</Tag>
          ) : (
            <Tag color="#108ee9">真人</Tag>
          );
        }
      },
      {
        title: "最近申请时间",
        dataIndex: "applyTime",
        key: "applyTime"
      },
      {
        title: "提现金额",
        dataIndex: "amount",
        key: "amount"
      },
      {
        title: "收款地址",
        dataIndex: "bankNo",
        key: "bankNo"
      }
    ];
    if (isAdmin) {
      columns.push({
        title: "操作",
        dataIndex: "actions",
        key: "actions",
        fixed: "right",
        render: (value, data) => {
          return (
            <span>
              <Button
                size={"small"}
                type="danger"
                onClick={() => this.reject(data)}
              >
                驳回
              </Button>
              <Button
                size={"small"}
                style={{ marginLeft: 10 }}
                type="primary"
                onClick={() => this.setAlreadyPay(data)}
              >
                设为已打款
              </Button>
            </span>
          );
        }
      });
    }
    return (
      <div>
        <MyForm
          initForm={initForm}
          items={formItmes}
          handleSearch={this.handleSearch}
        />
        <Spin spinning={loading}>
          {/*{isAgent || isChannel ? null : (*/}
          {/*  <div style={{ marginBottom: 20 }}>*/}
          {/*    <Button*/}
          {/*      type={"primary"}*/}
          {/*      onClick={this.handleOpenSettlementApplyDlg}*/}
          {/*    >*/}
          {/*      申请提现*/}
          {/*    </Button>*/}
          {/*  </div>*/}
          {/*)}*/}
          <Table
            dataSource={tableData.rows}
            columns={columns}
            pagination={false}
            scroll={{ x: true }}
          />
          <Pagination
            style={{ marginTop: 10, marginBottom: 20 }}
            total={tableData.total}
            showTotal={total => `共 ${total} 项`}
            pageSizeOptions={["10", "20", "50", "100", "500"]}
            showSizeChanger
            onShowSizeChange={this.onShowSizeChange}
            pageSize={pageSize}
            current={curPage}
            onChange={this.handlePageChange}
          />
          <Modal
            title="添加商户提现"
            visible={this.state.settlementApplyDig}
            onCancel={this.handleCloseSettlementApplyDlg}
            width={700}
            footer={null}
          >
            {this.state.settlementApplyDig ? (
              <SettlementApplyForm
                handleApplyOk={this.handleCloseSettlementApplyDlg}
                inDlg={true}
              />
            ) : null}
          </Modal>
        </Spin>
      </div>
    );
  }
}

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(withRouter(CashRecord));
